import numpy as np
import csv
import matplotlib.pyplot as plt

from scipy.interpolate import make_interp_spline
import pandas


adc = []
# 记录高度跟adc的数据表，无表头索引
# 高度0-键程以上高一点，步进0.05，多一点方便程序判断触底高度
# adc 根据实际情况记录

file_name = 'xxx.csv'
csv_file = open(file_name, 'r')
csv_reader = csv.reader(csv_file, delimiter=',')

for row in csv_reader:
    adc.append(row)

height = [round(float(i[0]), 2) for i in adc]
adc    = [round(float(i[1]), 3) for i in adc]

adc0 = adc[0]
adc = [adc[0] - i for i in adc]

height = np.array(height)
adc = np.array(adc)

dx = height[1:] - height[:-1]
dy = adc[1:] - adc[:-1]
slopes = np.diff(dy/dx)

# 根据数据分辨率，修改turning_point_threshold
turning_point_threshold = 1000
tp = (np.where(np.abs(np.diff(slopes)) > turning_point_threshold)[0] + 2)[0]

k = (dy[tp] - dy[tp+1]) / (dy[tp-1] - dy[tp+1])
bot_height = float(height[tp] + k * dx[0])
bot_adc = float(adc[tp] + k * dy[tp-1])

bot_height = round(bot_height, 3)
bot_adc = round(bot_adc, 3)
print(file_name)
print("%1.3f" % bot_height)

model0 = make_interp_spline(height, adc)
x = np.linspace(0, height[-1], int(height[-1]*1000)+1)

ys0 = model0(x)

plt.plot(x, ys0)
plt.xlim((bot_height-0.2, bot_height+0.2))

plt.scatter(bot_height, bot_adc, c='r')
plt.scatter(height[tp], adc[tp], c='b')
plt.scatter(height[tp+1], adc[tp+1], c='b')
plt.show()

adc_list = []
height_list = []

for i in range(tp+1):
    adc_list.append(-adc[i] + adc0)
    height_list.append(height[i])

if bot_height > height[tp]:
    adc_list.append(-bot_adc + adc0)
    height_list.append(bot_height)

if bot_height < height[tp]:
    adc_list[-1] = -bot_adc + adc0
    height_list[-1] = bot_height

df = pandas.DataFrame(data={"height": height_list, "adc": adc_list})
filepath = file_name + '.xlsx'
df.to_excel(filepath, index=False, header=False)
